﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.IO;

using Hangjing.SQLServerDAL;
using Hangjing.Common;
using Hangjing.Model;

using org.in2bits.MyXls;
using Hangjing.AppLog;
// 商家餐品信息管理
// CopyRight (c) 2009-2010 HangJing Teconology. All Rights Reserved.
// zjf@ihangjing.com 餐品信息

public partial class Admin_shop_FoodDetail :AdminPageBase
{
    Points daltogo = new Points();
    FoodStyle dalsf = new FoodStyle();
    FoodAttributes dalfa = new FoodAttributes();

    protected void Page_Load(object sender, EventArgs e)
    {
        ValidatorSet validator = new ValidatorSet("Admin");
        validator.SetValidator();
        CheckRights("A");
        if (!IsPostBack)
        {
            GetFoodSort();
            //编辑
            int FPMaster = HjNetHelper.GetQueryInt("tid", 0);
            int Unid = HjNetHelper.GetQueryInt("id", 0);
            HdUnid.Value = Unid.ToString();
            this.hidTogoId.Value = FPMaster.ToString();

            PointsInfo info = daltogo.GetModel(FPMaster);
            this.lbtogo.Text = info.Name;
            hidDataId.Value = Unid.ToString();

            if (Unid > 0)
            {
                BindFoodData(Unid);
                pageType.Text = "更新餐品";
                pricebox.Style["display"] = "none";
            }
            else
            {
                pageType.Text = "新增餐品";
                rblfoodno.Items[0].Selected = true;
                
                rblIsSpecial.Items[0].Selected = true;
            }
           
        }
    }

    Foodinfo dal = new Foodinfo();
    EFoodSort dal_sort = new EFoodSort();
    AllFoods dal_allfoods = new AllFoods();

    protected void BindFoodData(int Unid)
    {
        FoodinfoInfo model = dal.GetModel(Unid);
        if (model != null)
        {
            this.tbNamefx.Text = model.FoodName;
            this.lbtogo.Text = model.TogoName.ToString();

            this.ddlFoodType.SelectedValue = model.FoodType.ToString();
            this.tbPrice.Text = model.FPrice.ToString();
            this.tbFoodNamePy.Text = model.FoodNamePy;
            this.tbtaste.Text = model.Taste;
          
            ddlIsUse.SelectedValue = model.InUse.ToString();
            tbOrderNum.Text = model.OrderNum.ToString();

            tbIsRecommend.Text = model.IsRecommend.ToString();
            rblIsSpecial.SelectedValue = model.IsSpecial.ToString();
            if (!string.IsNullOrEmpty(model.Picture))
            {
                ImgUrl.Src = WebUtility.ShowPic(model.Picture);
            }
            this.ImgUrl1.Value = model.Picture;
            WebUtility.SelectValue(rblfoodno, model.FoodNo);
            tbRemains.Text = model.Remains.ToString();
            tbFullPrice.Text = model.FullPrice.ToString();
            GetStyle();
        }
    }

    protected void btSave_Click(object sender, EventArgs e)
    {
        if (IsRefresh)
        {
            return;
        }

        FoodinfoInfo model = new FoodinfoInfo();
        model.Unid = HjNetHelper.GetQueryInt("id", 0);
        if (model.Unid > 0)
        {
            model = dal.GetModel(model.Unid);
        }
        else
        {
            model.OpenTime = "1";
            model.isauth = 0;
        }

        model.InUse = ddlIsUse.SelectedValue.ToString();
        model.FoodName = WebUtility.InputText(this.tbNamefx.Text);
        model.FoodNo = rblfoodno.SelectedValue;
        model.FPrice = Convert.ToDecimal(this.tbPrice.Text);
        model.FPInDate = DateTime.Now;
        model.FPActiveDate = DateTime.Now;
        model.FPMaster = HjNetHelper.GetQueryInt("tid", 0);
        model.FoodNamePy = WebUtility.InputText(this.tbFoodNamePy.Text);
        model.FullPrice = Convert.ToDecimal(this.tbFullPrice.Text);
        model.Remains = WebUtility.InputText(tbRemains.Text, true);
        model.MaxPerDay = 0;
        model.Taste = this.tbtaste.Text;
        model.Picture = ImgUrl1.Value;
        model.FoodType = Convert.ToInt32(ddlFoodType.SelectedValue);
        model.OrderNum = Convert.ToInt32(tbOrderNum.Text);
        model.IsRecommend = Convert.ToInt32(tbIsRecommend.Text);
        model.IsSpecial = Convert.ToInt32(rblIsSpecial.SelectedValue);
     
        if (pageType.Text == "新增餐品")
        {
            //判断权限
            int _rs = WebUtility.checkOperator(2);
            if (_rs == 0)
            {
                AlertScript.RegScript(this.Page, "alert('无操作权限','success','true',5);init();");
                return;
            }

            int foodid = dal.Add(model);

            if (foodid > 0)
            {
                this.tbNamefx.Text = "";
                this.tbPrice.Text = "";
                tbtaste.Text = "";
                ImgUrl.Src = WebUtility.ShowPic(model.Picture);


                string url = "FoodDetail.aspx?tid=" + model.FPMaster + "&id=" + foodid;
                AlertScript.RegScript(this.Page, "alert('添加成功','success','true',5);gourl('" + url + "');");


            }
            else
            {
                AlertScript.RegScript(this, "showMessage('添加失败','error','true','8');");
            }
        }
        else
        {
            model.Unid = HjNetHelper.GetQueryInt("id", 0);
            if (model.Unid != 0)
            {
                //判断权限
                int _rs = WebUtility.checkOperator(3);
                if (_rs == 0)
                {
                    AlertScript.RegScript(this.Page, "alert('无操作权限','success','true',5);init();");
                    return;
                }
                if (dal.Update(model) == 1)
                {
                    AlertScript.RegScript(this, "showMessage('修改成功','success','true','5');");
                    ImgUrl.Src = WebUtility.ShowPic(model.Picture);
                }
                else
                {
                    AlertScript.RegScript(this, "showMessage('修改失败','error','true','8');");
                }
            }
        }
        Hangjing.Cache.EasyEatCache.GetCacheService().RemoveObject("/shop/shop" + HjNetHelper.GetQueryInt("tid", 0) + "/food");
    }

    protected void GetFoodSort()
    {
        int tid = HjNetHelper.GetQueryInt("tid", 0);
        IList<EFoodSortInfo> list = dal_sort.GetListByTogoNum(tid);
        if (list.Count == 0)
        {
            string js = "alert('您还没有为此商家添加一个分类,点击确定添加分类');gourl('FoodSortDetail.aspx?tid=" + tid + "');";
            AlertScript.RegScript(Page, js);
            return;
        }
        WebUtility.BindList<EFoodSortInfo>("SortID", "SortName", list, ddlFoodType);
    }

    /// <summary>
    /// 批量导入菜品数据 获取excel表格
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btAddExcel_Click(object sender, EventArgs e)
    {
        PinYin npy = new PinYin();
        if (IsRefresh)
        {
            return;
        }

        string suffix = Path.GetExtension(this.fuFoodExcel.PostedFile.FileName);
        string sFile =  "~/admin/upload/foodexcel/"+HjNetHelper.GetQueryString("tid")+"" + System.DateTime.Now.ToString("yyyyMMddHHmmssffff") + suffix;  //上传后文件的新名

        string errorinfo = "";

        if (suffix == ".xls" || suffix == ".XLS")
        {
            //保存文件
            try
            {
                this.fuFoodExcel.PostedFile.SaveAs(Server.MapPath(sFile));
            }
            catch(Exception ex)
            {
                //log.AddSystemLog(ex.Message, LogType.Error, "AddExcelFood");
                AppLog.Error(ex.Message);

                AlertScript.RegScript(this, "tipsWindown('提示信息','text:保存文件出错,稍后再试或联系技术人员','250','150','true','1000','true','text');");
                return;
            }

            //获取商家的商品分类，excel中菜品的分类使用的是中文，需要进行匹配得到分类的编号保存到数据库菜品表中
            IList<EFoodSortInfo> foodtypelist = new List<EFoodSortInfo>();
            EFoodSort foodsortdal = new EFoodSort();

            //必要的判断以防止excel格式的问题导致程序错误

            foodtypelist = foodsortdal.GetListByTogoNum(HjNetHelper.GetQueryInt("tid", 0));

            //AppLog.Debug(foodtypelist.Count);

            if (foodtypelist == null || foodtypelist.Count < 1)
            {
                AlertScript.RegScript(this, "tipsWindown('提示信息','text:商家菜品分类为空，至少需要一个菜品分类，请先添加菜品分类后进行导入操作','250','150','true','','true','text');");
                return;
            }
            else
            {
                try
                {
                    //解析文件并保存数据到数据库
                    XlsDocument xls = new XlsDocument(Server.MapPath(sFile));
                    Worksheet sheet = xls.Workbook.Worksheets["ShopFood"];

                    FoodinfoInfo info;

                    Foodinfo bll = new Foodinfo();

                    int togoid = HjNetHelper.GetQueryInt("tid", 0);

                    bool havesort = false;
                    //餐品名称、餐品原价、餐品现价、餐品库存、分类名称
                    for (int i = 2; i < sheet.Rows.Count; i++) //excel中行数从1开始 此处第一行是行名称所以跳过第一个
                    {
                        if (sheet.Rows[ushort.Parse(i.ToString())] != null && sheet.Rows[ushort.Parse(i.ToString())].CellCount > 0)
                        {
                            info = new FoodinfoInfo();

                            info.FPMaster = togoid;

                            info.FoodName = sheet.Rows[ushort.Parse(i.ToString())].GetCell(ushort.Parse("1")).Value.ToString();
                            info.FPrice = Convert.ToDecimal(sheet.Rows[ushort.Parse(i.ToString())].GetCell(ushort.Parse("2")).Value);
                            info.FullPrice = Convert.ToDecimal(sheet.Rows[ushort.Parse(i.ToString())].GetCell(ushort.Parse("3")).Value);
                            info.MaxPerDay = Convert.ToInt32(sheet.Rows[ushort.Parse(i.ToString())].GetCell(ushort.Parse("4")).Value);
                            //此处如果无内容则 列数会变成6，此时如果依然不做判断会报错超出数组范围，注意其他地方使用此类方法时注意此问题,
                            //空值的单元格并非为空而是直接超出数组范围
                            if (sheet.Rows[ushort.Parse(i.ToString())].CellCount > 6)
                            {
                                info.Taste = sheet.Rows[ushort.Parse(i.ToString())].GetCell(ushort.Parse("6")).Value.ToString();
                            }
                            else
                            {
                                info.Taste = "";
                            }
                            //进行分类判断
                            foreach (EFoodSortInfo sortinfo in foodtypelist)
                            {
                                if (sortinfo.SortName == sheet.Rows[ushort.Parse(i.ToString())].GetCell(ushort.Parse("5")).Value.ToString().Trim())
                                {
                                    info.FoodType = sortinfo.SortID;

                                    havesort = true;
                                    break;
                                }
                            }
                            if (!havesort)
                            {
                                info.FoodType = foodtypelist[0].SortID;//默认为使用第一个分类

                                errorinfo += "菜品[" + info.FoodName + "]未找到匹配的分类稍后请手动设置其分类；<br />";
                            }

                            havesort = false;


                            info.FoodNamePy = npy.convert(info.FoodName, true);
                            info.FoodNo = "";
                            info.FPActiveDate = DateTime.Now;
                            info.FPInDate = DateTime.Now;
                            info.InUse = "Y";
                            info.Picture = "";
                            info.Remains = info.MaxPerDay;
                            //info.Taste = "";
                            info.OrderNum = 0;
                            info.IsRecommend = 0;
                            info.IsSpecial = 0;
                            info.isauth = 0;
                            info.OpenTime = "1";
                            bll.Add(info);
                        }
                    }
                }
                catch (Exception ex)
                {
                    AppLog.Error(ex.Message);
                }
            }

            AlertScript.RegScript(this, "$('#doing-mask').hide();tipsWindown('提示信息','text:批量导入成功,消息：" + errorinfo + "!','250','150','true','','true','text');");//
        }
        else
        {
            AlertScript.RegScript(this, "$('#doing-mask').hide();tipsWindown('提示信息','text:文件格式不正确，请上传excel文件!','250','150','true','','true','text');");
        }
        Hangjing.Cache.EasyEatCache.GetCacheService().RemoveObject("/shop/shop" + HjNetHelper.GetQueryInt("tid", 0) + "/food");
    }

    protected void GetStyle()
    {
        int FoodId = HjNetHelper.GetQueryInt("id", 0);
        rptFoodlist.DataSource = dalsf.GetList(10, 1, "FoodtId =" + FoodId, "dataid", 0);
        rptFoodlist.DataBind();

        rptattr.DataSource = dalfa.GetList(20, 1, "FoodtId =" + FoodId, "dataid", 0);
        rptattr.DataBind();
    }

    protected void rptFoodlist_ItemCommand(object sender, RepeaterCommandEventArgs e)
    {
        string type = e.CommandName;
        switch (type)
        {
            case "del":
                if (dalsf.DelProductStyle(Convert.ToInt32(e.CommandArgument)) > 0)
                {
                    AlertScript.RegScript(this.Page, "alert('删除成功','text:删除成功!','250','150','true','1000','true','text');init();");
                    GetStyle();
                    new Foodinfo().UpdateFooodPrice(HjNetHelper.GetQueryInt("id", 0));
                }
                else
                {
                    AlertScript.RegScript(this.Page, "alert('删除失败','text:删除失败!','250','150','true','1000','true','text');init();");
                }
                break;
        }
    }

    protected void rptattr_ItemCommand(object sender, RepeaterCommandEventArgs e)
    {
        string type = e.CommandName;
        switch (type)
        {
            case "del":
                if (dalfa.DelProductAttributes(Convert.ToInt32(e.CommandArgument)) > 0)
                {
                    AlertScript.RegScript(this.Page, "alert('删除成功','text:删除成功!','250','150','true','1000','true','text');init();");
                    GetStyle();
                    new Foodinfo().UpdateFooodAttr(HjNetHelper.GetQueryInt("id", 0));
                }
                else
                {
                    AlertScript.RegScript(this.Page, "alert('删除失败','text:删除失败!','250','150','true','1000','true','text');init();");
                }
                break;
        }
    }
}

